package all.com.jinyongqunxiax.modules;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.randy.fundation.ImageUitls;
import com.randy.fundation.Logger;
import com.randy.fundation.MD5Utils;

import org.apache.commons.io.FilenameUtils;

import java.io.FileOutputStream;

import all.com.jinyongqunxiax.R;
import all.com.jinyongqunxiax.model.mod.DataManager;
import all.com.jinyongqunxiax.model.mod.manager.Mod;
import all.com.jinyongqunxiax.model.mod.manager.ModManager;
import all.com.jinyongqunxiax.model.mod.ResourceManager;
import all.com.jinyongqunxiax.view.JxHud;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import jy.game.components.resource.JyResource;

public class ImageDetailActivity extends AppCompatActivity {
    static final int RC_PICK_IMAGE_FROM_NETWORK = 1;
    static final int RC_PICK_IMAGE_FROM_PHOTO   = 2;
    Options options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_detail_activity);

        options = new Options(getIntent());


        String itemName = FilenameUtils.concat(options.component, options.item);
        setTitle(itemName);

        String          itemKey = FilenameUtils.removeExtension(itemName);
        Mod             mod     = ModManager.shared().get(options.mod);
        ResourceManager manager = mod.resourceManager;
        loadData(mod);

        JyResource resource         = manager.resourcesByValue.get(itemKey);
        TextView   resourceTextView = findViewById(R.id.image_detail_resourceTextView);
        if (resource != null) {
            resourceTextView.setText(resource.key);
        } else {
            resourceTextView.setText("资源不存在");
            Logger.e("cannot get resource for %s", itemKey);
            JxHud.alert("cannot get resource for %s", itemKey);
        }

        Button replaceButton = findViewById(R.id.image_detail_replaceButton);
        replaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickImage();
            }
        });
        Button fixButton = findViewById(R.id.image_detail_fixButton);
        fixButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fixImage();
            }
        });
    }

    @SuppressLint("SetTextI18n")
    void loadData(Mod mod) {
        String path = FilenameUtils.concat(options.mod, options.component);
        path = FilenameUtils.concat(path, options.item);

        ImageView imageView = findViewById(R.id.image_detail_imageView);
        Glide.with(this).load(path)
             .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
             .apply(RequestOptions.skipMemoryCacheOf(true))
             .into(imageView);

        String itemKey = FilenameUtils.concat(options.component, options.item);
        itemKey = FilenameUtils.removeExtension(itemKey);

        DataManager      manager  = mod.dataManager;
        DataManager.Data data     = manager.datas.get(itemKey);
        TextView         textView = findViewById(R.id.image_detail_hashTextView);
        if (data != null) {
            String fileHash = MD5Utils.fileMD5(path);
            if (TextUtils.isEmpty(fileHash)) {
                textView.setText(data.hash + "\n" + "-");
            } else if (fileHash.equals(data.hash)) {
                textView.setText(fileHash);
            } else {
                textView.setText(data.hash + "\n" + fileHash);
            }

            ImageUitls.ImageSize size = ImageUitls.getImageSize(path);

            TextView widthTextView = findViewById(R.id.image_detail_widthTextView);
            widthTextView.setText(size.width + "," + data.width + "," + options.width);

            TextView heightTextView = findViewById(R.id.image_detail_heightTextView);
            heightTextView.setText(size.height + "," + data.height + "," + options.height);
        } else {
            textView.setText("资源不存在");
            Logger.e("cannot get data for %s", itemKey);
        }
    }

    public void pickImage() {
        // setup the alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择图片获取方式:");

        // add a list
        String[] animals = {"相册", "网络"};
        builder.setItems(animals, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        pickImageFromPhoto();
                        break;
                    case 1:
                        pickImageFromNetwork();
                        break;
                    default:
                        Logger.w("not handle option:%d", which);
                }
            }
        });

        // create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    void pickImageFromPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("scale", true);
        intent.putExtra("outputX", options.width);
        intent.putExtra("outputY", options.height);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RC_PICK_IMAGE_FROM_PHOTO);
    }

    void pickImageFromNetwork() {
        Intent intent = ImagePickNetworkBaiduActivity.Options.intent(this, options.width, options.height);
        startActivityForResult(intent, RC_PICK_IMAGE_FROM_NETWORK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RC_PICK_IMAGE_FROM_NETWORK:
            case RC_PICK_IMAGE_FROM_PHOTO:
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap image = extras.getParcelable("data");
                    if (image == null || image.getWidth() == 0) {
                        Toast.makeText(this, "pick image failed", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, image.getWidth() + "x" + image.getHeight(), Toast.LENGTH_LONG).show();
                        replaceImage(image);
                    }
                }
                break;
            default:
                Logger.w("not handle request:%d", requestCode);
                break;

        }
    }

    void fixImage() {
        Mod mod = ModManager.shared().get(options.mod);

        String path = FilenameUtils.concat(options.mod, options.component);
        path = FilenameUtils.concat(path, options.item);

        String itemKey = FilenameUtils.concat(options.component, options.item);
        itemKey = FilenameUtils.removeExtension(itemKey);

        DataManager      manager = mod.dataManager;
        DataManager.Data data    = manager.datas.get(itemKey);

        if (data == null) {
            return;
        }

        ImageUitls.ImageSize size = ImageUitls.getImageSize(path);
        if (size.width != data.width) {
            data.width = size.width;
            data.height = size.height;
        }

        // 保存结果
        manager.save();
        // 重新加载
        loadData(mod);
    }

    void replaceImage(Bitmap bitmap) {
        String path = FilenameUtils.concat(options.mod, options.component);
        path = FilenameUtils.concat(path, options.item);
        FileOutputStream stream = null;
        try {
            String ext = FilenameUtils.getExtension(path);
            stream = new FileOutputStream(path);

            if ("jpg".equals(ext) || "jpeg".equals(ext)) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            } else {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Mod mod = ModManager.shared().get(options.mod);
        // 重新计算md5
        mod.updateMD5(options.component, options.item);
        // 重新加载
        loadData(mod);
    }

    public static class Options {
        String mod;
        String component;
        String item;
        int    width;
        int    height;
        Options(Intent intent) {
            this.mod = intent.getStringExtra("mod");
            this.component = intent.getStringExtra("component");
            this.item = intent.getStringExtra("item");

            this.width = intent.getIntExtra("width", 0);
            this.height = intent.getIntExtra("height", 0);
        }

        static Intent intent(Context context, String mod, String component, String item, int width, int height) {
            Intent intent = new Intent(context, ImageDetailActivity.class);
            intent.putExtra("width", width);
            intent.putExtra("height", height);
            intent.putExtra("mod", mod);
            intent.putExtra("component", component);
            intent.putExtra("item", item);
            return intent;
        }
    }
}
